<script setup lang="ts">
  import { reactive, ref, useTemplateRef } from 'vue'
  import { useQuasar } from 'quasar'

  import CudTable, { type TQTableColumns, type TRequestParam } from '@/components/CudTable.vue'
  import {
    getRepairOrderPageList,
    type IRepairWorkeryParams,
    getRepairWorkerPageList,
    type IRepairOrderParams,
    type IRepairWorkerParam,
    addRepairWorker,
    editRepairWorker,
    removeRepairWorker
  } from '@/api'
  import { isRequestSuccess } from '@/utils'

  const $q = useQuasar()
  const tab = ref('repair-man')
  function refreshGridData(tableRef: any) {
    if (tableRef.value) {
      tableRef.value.refreshUserTable(1)
    }
  }
  type TCudTable = InstanceType<typeof CudTable>
  const classes = 'max-w-[160px] break-all'

  // repair worker

  const manColumns: TQTableColumns = [
    {
      name: 'maintenanceWorkerId',
      label: '维修工ID',
      field: 'maintenanceWorkerId',
      align: 'left',
      classes
    },
    { name: 'name', label: '姓名', field: 'name', align: 'left', classes },
    { name: 'idNumber', label: '身份证号', field: 'idNumber', align: 'left', classes },
    { name: 'phoneNumber', label: '电话', field: 'phoneNumber', align: 'left', classes },
    {
      name: 'maintenanceProject',
      label: '负责项目',
      field: 'maintenanceProject',
      align: 'left',
      classes
    },
    { name: 'actions', label: '操作', field: 'actions', align: 'left' }
  ]
  // query
  const manTableRef = useTemplateRef<TCudTable>('repair-man')
  const manFilter = ref('')
  function refreshWorderGridData() {
    refreshGridData(manTableRef)
  }
  function manRequest(context: TRequestParam) {
    const { page, rowsPerPage } = context.pagination
    const params: IRepairWorkeryParams = { pageNum: page, pageSize: rowsPerPage }
    if (manFilter.value !== '') {
      params.name = manFilter.value
    }
    return getRepairWorkerPageList(params)
  }
  function onManKeyInput(event: KeyboardEvent) {
    if (event.key.toLowerCase() === 'enter') {
      // 13 为回车键
      refreshWorderGridData()
    }
  }
  // repair worder add/edit
  let maintenanceWorkerId = -1
  const editRow: IRepairWorkerParam = {
    name: '',
    idNumber: '',
    phoneNumber: '',
    maintenanceProject: ''
  }
  const pEditRow = reactive<IRepairWorkerParam>(Object.assign({}, editRow))
  const rShowDialog = ref(false)
  async function onDialogSubmit() {
    const res = await (maintenanceWorkerId === -1
      ? addRepairWorker({ ...pEditRow })
      : editRepairWorker({ ...pEditRow, maintenanceWorkerId }))
    if (isRequestSuccess(res)) {
      $q.notify({
        type: 'positive',
        message: '提交成功'
      })
      refreshWorderGridData()
    } else {
      $q.notify({
        color: 'red-5',
        textColor: 'white',
        icon: 'warning',
        message: '提交失败'
      })
    }
    onCancel()
  }
  function onShowDialog(row?: any) {
    if (row) {
      maintenanceWorkerId = row.maintenanceWorkerId
    } else {
      maintenanceWorkerId = -1
      row = editRow
    }
    const keys = Object.keys(editRow) as (keyof IRepairWorkerParam)[]
    keys.forEach(key => {
      pEditRow[key] = row[key]
    })
    rShowDialog.value = true
  }
  function onCancel() {
    rShowDialog.value = false
  }
  function onRemove(row: any) {
    if (row) {
      $q.dialog({
        title: '确认',
        message: '你确定要删除这个条记录吗?',
        cancel: true,
        persistent: true
      }).onOk(() => {
        removeRepairWorker(row.maintenanceWorkerId)
          .then(res => {
            if (isRequestSuccess(res)) {
              refreshWorderGridData()
            }
          })
          .catch(error => {
            console.log(error)
          })
      })
    }
  }

  //  repair order
  const statusOptions = ['全部状态', '待分配', '维修中', '待审核', '已完成']
  const rStatus = ref('全部状态')
  const maintenanceProject = ref('')
  const orderTableRef = useTemplateRef<TCudTable>('repair-order')
  const orderColumns: TQTableColumns = [
    {
      name: 'maintenanceOrderId',
      label: '维修订单ID',
      field: 'maintenanceOrderId',
      align: 'left',
      classes
    },
    {
      name: 'maintenanceProject',
      label: '维修项目',
      field: 'maintenanceProject',
      align: 'left',
      classes
    },
    { name: 'faultContent', label: '故障明细', field: 'faultContent', align: 'left', classes },
    {
      name: 'maintenanceHouseNumber',
      label: '维修房屋编号',
      field: 'maintenanceHouseNumber',
      align: 'left',
      classes
    },
    {
      name: 'maintenanceName',
      label: '维修工姓名',
      field: 'maintenanceName',
      align: 'left',
      classes
    },
    { name: 'images', label: '图片', field: 'images', align: 'left', classes },
    {
      name: 'maintenanceVoucher',
      label: '维修凭证',
      field: 'maintenanceVoucher',
      align: 'left',
      classes
    },
    { name: 'status', label: '状态', field: 'status', align: 'left', classes }
  ]

  function orderRequest(context: TRequestParam) {
    const { page, rowsPerPage } = context.pagination
    const params: IRepairOrderParams = { pageNum: page, pageSize: rowsPerPage }
    if (rStatus.value !== '全部状态') {
      params.status = rStatus.value
    }
    if (maintenanceProject.value !== '') {
      params.maintenanceProject = maintenanceProject.value
    }
    return getRepairOrderPageList(params)
  }

  function refreshOrderGridData() {
    refreshGridData(orderTableRef)
  }
  function onKeyOrderInput(event: KeyboardEvent) {
    if (event.key.toLowerCase() === 'enter') {
      // 13 为回车键
      refreshOrderGridData()
    }
  }
</script>

<template>
  <q-page class="bg-[#FAFCFF] p-5">
    <q-tabs
      v-model="tab"
      dense
      active-color="primary"
      indicator-color="primary"
      align="left"
      narrow-indicator>
      <q-tab name="repair-man" label="维修工管理" />
      <q-tab name="repair-order" label="维修订单管理" />
    </q-tabs>

    <q-separator />

    <q-tab-panels v-model="tab" animated>
      <q-tab-panel name="repair-man">
        <CudTable
          ref="repair-man"
          class="bg-white"
          title="维修工管理"
          row-key="maintenanceWorkerId"
          :columns="manColumns"
          :request="manRequest">
          <template v-slot:body-cell-actions="{ row }">
            <td class="text-center">
              <span @click="onShowDialog(row)" class="text-[#2265D4] cursor-pointer">编辑</span>
              <span @click="onRemove(row)" class="text-[#EB4242] cursor-pointer ml-2">删除</span>
            </td>
          </template>
          <template v-slot:top-right>
            <q-input
              outlined
              dense
              @keydown="onManKeyInput"
              v-model="manFilter"
              placeholder="请输入姓名查询">
              <template v-slot:append>
                <q-icon name="search" @click="refreshWorderGridData" />
              </template>
            </q-input>
            <!--            <q-btn color="primary" class="ml-4" @click="onShowDialog()">
              <q-icon left size="1em" name="bi-plus-circle" />
              <div>新增</div>
            </q-btn>-->
          </template>
        </CudTable>
      </q-tab-panel>

      <q-tab-panel name="repair-order">
        <CudTable
          ref="repair-order"
          class="bg-white"
          title="维修订单管理"
          row-key="maintenanceOrderId"
          :columns="orderColumns"
          :request="orderRequest">
          <template v-slot:top-left>
            <p class="q-table__title flex items-center gap-3">
              <b>维修订单管理</b>
              <span class="text-[#999] text-xs">注：请前往小程序进行处理</span>
            </p>
          </template>
          <template v-slot:top-right>
            <q-input
              outlined
              dense
              debounce="500"
              v-model="maintenanceProject"
              @blur="refreshOrderGridData"
              @keydown="onKeyOrderInput"
              placeholder="请输入维修项目查询">
              <template v-slot:append>
                <q-icon class="cursor-pointer" name="search" @click="refreshGridData" />
              </template>
            </q-input>
            <q-select
              class="w-[200px] ml-3"
              outlined
              v-model="rStatus"
              @update:model-value="refreshOrderGridData"
              :options="statusOptions"
              dense
              options-dense></q-select>
          </template>
        </CudTable>
      </q-tab-panel>
    </q-tab-panels>
    <q-dialog v-model="rShowDialog" class="ud-dialog">
      <q-card class="!max-w-none w-[80%] flex flex-col no-wrap">
        <q-card-section class="text-h6 text-[#409EFD] relative">
          <div class="text-h6 text-[#409EFD] relative">
            <b class="v-blue-line"></b>
            维修工管理
          </div>
        </q-card-section>

        <q-form @submit="onDialogSubmit" class="flex-1 flex flex-col">
          <div class="flex-1 px-8">
            <q-card-section horizontal>
              <div class="w-[143px] text-right text-lg text-[#333]">姓名：</div>
              <q-input
                class="flex-1 pb-0"
                v-model="pEditRow.name"
                outlined
                dense
                placeholder="请输入姓名"
                hint=""
                lazy-rules
                :rules="[val => !!val || '请输入姓名']"></q-input>
            </q-card-section>
            <q-card-section horizontal class="mt-5">
              <div class="w-[143px] text-right text-lg text-[#333]">身份证号：</div>
              <q-input
                class="flex-1 pb-0"
                v-model="pEditRow.idNumber"
                outlined
                dense
                placeholder="请输入身份证号"
                hint=""
                lazy-rules
                :rules="[val => !!val || '请输入身份证号']"></q-input>
            </q-card-section>
            <q-card-section horizontal class="mt-5">
              <div class="w-[143px] text-right text-lg text-[#333]">电话：</div>
              <q-input
                class="flex-1 pb-0"
                v-model="pEditRow.phoneNumber"
                outlined
                dense
                placeholder="请输入电话"
                hint=""
                lazy-rules
                :rules="[val => !!val || '请输入电话']"></q-input>
            </q-card-section>
            <q-card-section horizontal class="mt-5">
              <div class="w-[143px] text-right text-lg text-[#333]">负责项目：</div>
              <q-input
                class="flex-1 pb-0"
                v-model="pEditRow.maintenanceProject"
                outlined
                dense
                placeholder="请输入负责项目"
                hint=""
                lazy-rules
                :rules="[val => !!val || '请输入负责项目']"></q-input>
            </q-card-section>
          </div>

          <div class="flex flex-center gap-7 pb-5 mt-5">
            <q-btn
              color="blue-6"
              padding="10px 40px"
              text-color="white"
              label="确认"
              type="submit" />
            <q-btn outline padding="10px 40px" @click="onCancel" color="light-blue" label="取消" />
          </div>
        </q-form>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<style scoped></style>
